<script setup lang="ts">
import AMapLoader from '@amap/amap-jsapi-loader'
import AddressParse from 'zh-address-parse'
import '@amap/amap-jsapi-types'
import { regeoAPI } from '@/apis/regeo'
import markerIcon from '@/static/images/marker.png'
import { useBeforeOrderStore } from '@/store/beforeOrder'

const router = useRouter()
const beforeOrderStore = useBeforeOrderStore()

/* -------------------------------- 地图 START -------------------------------- */
let amap: typeof AMap
let map: AMap.Map
let marker: AMap.Marker

onShow(async () => {
  await loadMap()
  initMap()
  initCenterMarker()
  initGeolocationPlugin()
  addMoveEndListenerToMap()

  if (beforeOrderStore.from)
    map.panTo([beforeOrderStore.from.lng, beforeOrderStore.from.lat])
})

/**
 * @description 使用 key 与 securityCode 加载地图
 */
async function loadMap() {
  // 挂载安全密钥
  (window as any)._AMapSecurityConfig = {
    securityJsCode: import.meta.env.VITE_MAP_SECURITY_JS_CODE,
  }
  // 加载地图
  amap = await AMapLoader.load({
    key: import.meta.env.VITE_MAP_KEY,
    version: '2.0',
  })
}

/**
 * @description 初始化地图对象，将地图挂载到对应的 dom 元素中
 */
function initMap() {
  map = new amap.Map('map', {
    mapStyle: 'amap://styles/whitesmoke',
    zoom: 14,
  })
}

/**
 * @description 初始化一个 Marker，应当始终位于地图中央，当触发地图平移时间时应当更新此 Marker 的位置
 */
function initCenterMarker() {
  marker = new AMap.Marker({
    map,
    position: map.getCenter(),
    anchor: 'bottom-center',
    icon: markerIcon,
  })
  map.add(marker)
}

/**
 * @description 初始化定位插件，在加载地图时将地图中心设置为当前位置
 */
function initGeolocationPlugin() {
  amap.plugin('AMap.Geolocation', () => {
    const geolocation = new (amap as any).Geolocation({
      enableHighAccuracy: true,
      timeout: 10000,
      position: 'RB',
      offset: [20, 40],
      zoomToAccuracy: true,
    })
    map.addControl(geolocation)
    geolocation.getCurrentPosition(onPositionComplete)
  })

  /**
   * @description 获取当前位置的回调，在这里根据获取到的经纬度解析为具体地址并存入 store
   *
   * @param status - 获取定位的状态
   * @param result - 获取定位的结果
   */
  async function onPositionComplete(status: string, result: any) {
    if (status !== 'complete')
      return
    const res = await regeoAPI({ location: `${result.position.lng},${result.position.lat}` })
    if (!res.data?.regeocode.formatted_address) {
      uni.showToast({ title: '获取定位失败', icon: 'none' })
      return
    }
    beforeOrderStore.from = {
      lng: result.position.lng,
      lat: result.position.lat,
      name: AddressParse(res.data?.regeocode.formatted_address).detail,
    }
    beforeOrderStore.city = res.data.regeocode.addressComponent.city
  }
}

/**
 * @description 为地图添加平移事件的回调
 */
function addMoveEndListenerToMap() {
  map.on('mapmove', onMapMove)
  map.on('moveend', onMoveEnd)

  /**
   * @description 地图平移事件的回调，
   * 使用平移过后的地图中心点设置 Marker 的位置
   */
  async function onMapMove() {
    const center = map.getCenter()
    marker.setPosition([center.lng, center.lat])
  }

  /**
   * @description 地图平移结束事件的回调，
   * 使用平移过后的地图中心点解析为具体位置更新到 store
   */
  async function onMoveEnd() {
    const center = map.getCenter()
    const res = await regeoAPI({ location: `${center.lng},${center.lat}` })
    if (!res.data?.regeocode.formatted_address) {
      uni.showToast({ title: '获取定位失败', icon: 'none' })
      return
    }
    beforeOrderStore.from = {
      lng: center.lng,
      lat: center.lat,
      name: AddressParse(res.data?.regeocode.formatted_address).detail,
    }
  }
}
/* --------------------------------- 地图 END --------------------------------- */

/* ---------------------------- 新人优惠券弹窗 START --------------------------- */
const isShowNewUserCouponModal = ref(false)

onLoad(() => {
  if (!uni.getStorageSync('isClaimedNewUserCoupon')) {
    isShowNewUserCouponModal.value = true
    uni.setStorageSync('isClaimedNewUserCoupon', true)
  }
})
/* ----------------------------- 新人优惠券弹窗 END ---------------------------- */

/**
 * @description 跳转至选择位置页面
 * @param type 选择上车点还是下车点的位置
 */
function handleChooseLocation(type: '上车点' | '下车点') {
  router.push({
    name: 'chooseLocation',
    params: {
      type,
      navigationDestination: 'call',
      initialValue: type === '上车点'
        ? beforeOrderStore.from?.name || ''
        : '',
    },
  })
}

/**
 * @description 跳转至城际合成页面
 */
function handleViewIntercityList() {
  router.push({
    name: 'intercityList',
  })
}

/**
 * @description 跳转至为他人叫车页面
 */
function handleCallACarForSomeone() {
  router.push({
    name: 'callForSomeone',
  })
}

/**
 * @description 跳转至捎件页面
 */
function handleTapDelivery() {
  router.push({
    name: 'delivery',
  })
}

/**
 * @description 跳转至领取优惠券页面
 */
function handleViewCouponList() {
  router.push({
    name: 'claimCoupon',
  })
}
</script>

<template>
  <!-- 顶部蓝色的遮罩 -->
  <image
    class="fixed left-0 top-0 z-50 h-244rpx w-screen"
    src="@/static/images/gradient_blue.png"
  />
  <!-- 自定义状态栏 -->
  <NavigationBar title="通达电召" :is-show-back-button="false" title-font-size="54" />
  <!-- 地图 -->
  <view id="map" class="fixed left-0 top-0 h-[46vh] w-screen" />
  <!-- 底部操作面板 -->
  <view class="fixed bottom-0 left-0 h-[57vh] w-screen overflow-scroll rounded-tl-20rpx rounded-tr-20rpx bg-#F8F8F8 px-24rpx py-30rpx">
    <!-- 上下车点选择 -->
    <view class="rounded-30rpx bg-white px-30rpx py-40rpx">
      <view class="flex items-center px-21rpx text-30rpx text-#333333 font-bold leading-30rpx" @tap="handleChooseLocation('上车点')">
        <text class="mr-20rpx flex-none">
          在
        </text>
        <text v-if="beforeOrderStore.from?.name" class="text-#3F8BF6">
          {{ beforeOrderStore.from.name }}
        </text>
        <image
          v-else
          class="h-30rpx w-30rpx animate-spin"
          src="@/static/images/loading.png"
        />
        <text class="ml-20rpx flex-none">
          上车 >
        </text>
      </view>
      <Spacer height="38" />
      <view
        class="h-98rpx flex items-center border-3rpx border-black rounded-20rpx border-solid px-22rpx text-36rpx font-bold leading-36rpx"
        @tap="handleChooseLocation('下车点')"
      >
        请输入您的目的地
      </view>
    </view>
    <Spacer height="20" />
    <!-- 城际合成、一键代叫、一键捎件 -->
    <view class="flex justify-between">
      <image
        class="h-245rpx w-341rpx"
        src="@/static/images/home_action_0.jpg"
        @tap="handleViewIntercityList"
      />
      <view class="h-245rpx flex flex-col justify-between">
        <image
          class="h-113rpx w-341rpx"
          src="@/static/images/home_action_1.png"
          @tap="handleCallACarForSomeone"
        />
        <image
          class="h-113rpx w-341rpx"
          src="@/static/images/home_action_2.png"
          @tap="handleTapDelivery"
        />
      </view>
    </view>
    <Spacer height="20" />
    <!-- 优惠券 -->
    <image
      class="h-192rpx w-702rpx"
      src="@/static/images/home_action_coupon.png"
      @tap="handleViewCouponList"
    />
    <Spacer height="200" />
  </view>

  <uv-overlay :show="isShowNewUserCouponModal" @tap="isShowNewUserCouponModal = false">
    <uv-transition mode="zoom-in" :show="isShowNewUserCouponModal">
      <view class="relative h-screen w-screen">
        <CouponModal @close="isShowNewUserCouponModal = false" />
      </view>
    </uv-transition>
  </uv-overlay>
</template>

<route lang="yaml">
name: 'home'
style:
  navigationStyle: 'custom'
layout: 'custom'
</route>
